from Crypto.Cipher import  AES
from urllib import parse,request
import  base64
import re
import os
import  sys

headers={'Cookie': 'appver=1.5.0.75771;','Referer': 'http://music.163.com/','User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'}
b="010001"
c="00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
d="0CoJUm6Qyw8W8jud"
encSecKey = "257348aecb5e556c066de214e531faadd1c55d814f9be95fd06d6bff9f4c7a41f831f6394d5a3fd2e3881736d94a02ca919d952872e7d0a50ebfa1769a7a62d512f5f1ca21aec60bc3819a9c3ffca5eca9a0dba6d6f7249b06f5965ecfff3695b54e1c28f3f624750ed39e7de08fc8493242e26dbc4484a01c76f739e135637c"
iv="0102030405060708"
keyy='AES.MODE_CBC'
global  null
null=None
global false
false=0
def _AEC_encrypt(text,key):
    add_16=16-len(text)%16 #CBC加密特性
    if isinstance(text, str):
        text = text + add_16 * chr(add_16)
    else:
        text = text.decode('utf-8') +add_16* chr(add_16)

    encryptor=AES.new(key.encode('utf-8'),AES.MODE_CBC,iv.encode('utf-8'))
    encryptor_text=encryptor.encrypt(text.encode('utf-8'))
    return  base64.b64encode(encryptor_text)
def _get_params(a):
    encdText=_AEC_encrypt(a,d)
    i='F'*16
    encText=_AEC_encrypt(encdText,i)
    return  encText
def _get_post(url,params,encSecKey):

    data=parse.urlencode({"params":params,"encSecKey":encSecKey}).encode('utf-8')
    req=request.Request(url=url,headers=headers,data=data)
    page=request.urlopen(req)

    if(page!=None):
        sp = page.read().decode('utf-8')
        page_json=eval(sp)
        return page_json['data']
    else: return None
def get_name(id):

    return id
def run(music_id,s_name):
   # music_id = input('请输入歌的ID ：')
    url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
    music_ID = "{\"ids\":\"[%d]\",\"br\":128000,\"csrf_token\":\"\"}" % int(music_id)
    print(s_name,"  id:",music_id)
    params = _get_params(music_ID)
    res = _get_post(url, params, encSecKey)
   # s_name = input('输入歌名 ')
    s_na = s_name + ".mp3";
    s_na=s_na.replace(' ','_')
    s_na=s_na.replace('/','_')

    #print(res)
    if (res):
        s=res[0].get('url')
        if(s!=None):
         req=request.Request(url=s,headers=headers)
         music = request.urlopen(req)
         if(music):
              with open("网易云下载音乐/" + s_na, "wb") as f:
                f.write(music.read())
if not os.path.exists('网易云下载音乐/'):
    os.makedirs('网易云下载音乐/')
if __name__=='__main__':
 run(input('请输入音乐ID: '),input('请输入歌名: '))
#http://music.163.com/#/m/playlist?id=981261555